import React, { useEffect } from 'react'
import { Formik, FormikProps } from 'formik'
import { TextField } from '@material-ui/core'
import useRequest from '@rekindle/use-request'
import { useHistory } from 'react-router-dom'
import { useSnackbar } from 'notistack'
import { login } from '@/api/user'
import { Button } from '@/components'
import {
  Wrapper,
  Layout,
  FieldWraper,
  ButtonWrapper,
} from './style'

interface FormValues {
  account: string;
  password: string;
}

const Login: React.FC = () => {
  const [{ loading, error, data }, mutateLogin] = useRequest(login)
  const history = useHistory()
  const { enqueueSnackbar } = useSnackbar()

  function handleSubmit (values: FormValues): void {
    mutateLogin(values)
  }

  useEffect(() => {
    if (error) {
      enqueueSnackbar('error')
    }

    if (data) {
      window.localStorage.setItem('token', data.token)
      history.push('/dashboard')
    }
  }, [error, data])

  const initialValues: FormValues = {
    account: '',
    password: '',
  }

  const renderForm = (props: FormikProps<FormValues>): React.ReactElement => {
    return (
      <form onSubmit={props.handleSubmit}>
        <FieldWraper>
          <TextField
            type="text"
            fullWidth
            onChange={props.handleChange}
            value={props.values.account}
            name="account"
            placeholder="Please enter your account"
          />
          {props.errors.account && <div id="feedback">{props.errors.account}</div>}
        </FieldWraper>
        <FieldWraper>
          <TextField
            type="password"
            fullWidth
            onChange={props.handleChange}
            value={props.values.password}
            name="password"
            placeholder="password"
          />
          {props.errors.password && <div id="feedback">{props.errors.password}</div>}
        </FieldWraper>
        <ButtonWrapper>
          <Button type="submit" fullWidth loading={loading}>Login12</Button>
        </ButtonWrapper>
      </form>
    )
  }

  return (
    <Wrapper>
      <Layout>
        <Formik
          initialValues={initialValues}
          onSubmit={handleSubmit}
          render={renderForm}
        />
      </Layout>
    </Wrapper>
  )
}

export default Login
